#!/bin/csh -f
set echo_style=both
set commandline="$argv"
# PATHS
set SRCDIR=$DECAHOME/SRC
set EXEC=$DECAHOME/bin/d04_
set PHELP="awk -f $SRCDIR/pophelp.awk $SRCDIR/d04.help"
set LSOPT="$DECAHOME/scripts/lsopt d04"

# rarely changed options are defined here
set RSEED=1234 # seed for random number generator
set SAVEE=1000 # save energy in u.rep every SAVEE-th step
set HLW=1 # save config in copas.out every horiz loop, if NHL<=HLW
set SAVEXYZS=0 # save xyzs into a file for density plot
set IVI=1 # default vertical loops
set IHI=1 # default horizontal loops
set RELAXGAMMA="0.5" # GAMMA for relaxation
set DRAMAX="0.1" # max displacement for a relaxation step
set RCPLUS="1.0" #increase cutoff for construction of nn-tables for relax_para
set RCUTN="20.0" # cutoff for including tiling nodes for E-update
set FEPS="1e-6" # flip_union_eps
set NFD=2
set FLIPDEFS=(2 -2  1 -1) # flip_nu for allowed flips
# NOTE: moved swap* predefinition into file INPUT/D04/swap.def
#set swapsdef="-1 -1 0.5 3.0" # [short-swap]: MCS CH1 CH2 Rmin Rmax"
#set swapldef="-1 -1 0.5 7.0" # [long-swap]: MCS CH1 CH2 Rmin Rmax
set level=1 # update-level: level=1 is hexagon surface; N->+boundaries...
set tlevel=1
set nchp=0
set chpot=()
set chfi=
set chvar=
set fmantype=0
set norun=0

# other defaults
set FNAME="tiling.inp"
set TEST=0
set FORCETYPE0=0
set CHEMINP=0
set FLIPREC=0
set FLIPMAN=()
set RELAXMAN=0
set RELMANLIST=0
set SWAPMAN=0
set DFIT=0
set SWAP=0
set FLIP=0
set RELAX=0
set DBG=()
set RINP=0
set COUPLE=0
set NACT=0
set NACTR=0
set mc=""
set mcs=0
set mcname=0
set mcl=1 # multiplication factor for the mc schedule
set mct=0 # define linear mc schedule
set actions=0
set actname=0
set manu=0
set hcap=0
set cueff=0
set chpinp=0
set pin=0
set sigmaflip=0
set temper=0
########################### really start here ###############################
# check paths
if !(-e $SRCDIR) then
    echo "Directory $SRCDIR does not exist."
    echo "Probably env variable DECAHOME is not set (from .cshrc)."
    exit
endif
if !(-e $EXEC) then
    echo "Executable $EXEC does not exist."
    exit
endif

####### read defaults from  INPUT/D04/defaults
set def="INPUT/D04/defaults"
set argv_def=""
if ( -f $def ) then
    set argv_def=`awk 'NF>0{sub(/^ */,"");a=index($0,"#");c=$0;if(a>1){split($0,b,"#");c=b[1]}if(a!=1){cmd=cmd" -"c}}END{printf cmd}' $def`
#    echo "INPUT/FIG/defaults: $argv_def"
endif
########################### OPTIONS ###############################
set argv=($argv_def $argv)
#echo $argv
set act_tmp=".actions.tmp"
echo "# ACTIONS (cmdline)" > $act_tmp
while( "$*" != "" )
    switch ( $1 )
	case -set:
	    shift
	    switch ( $1 )
		case xyzs:
		    shift
		    set SAVEXYZS=$1
		breaksw
		case flipdef:
		    goto myflipdef
		breaksw
	    endsw
	breaksw
	case -flipdef:
myflipdef:
	    shift
	    set NFD=$1
	    set FLIPDEFS=()
	    @ i = 1
	    while( $i <= $NFD )
		shift
		set FLIPDEFS=($FLIPDEFS $1)
		shift
		set FLIPDEFS=($FLIPDEFS $1)
		@ i++
	    end
#	    echo $NFD $FLIPDEFS
#	    exit
	breaksw
	case -addflip:
	    @ NFD++
	    shift
	    set FLIPDEFS=($FLIPDEFS $1)
	    shift
	    set FLIPDEFS=($FLIPDEFS $1)
	breaksw
	case -feps:
	    shift
	    set FEPS=$1
	breaksw
	case -flip:
	    shift
	    @ actions++
	    echo "5 "$1" [NODE_FLIP: lab MCS]" >> $act_tmp
	breaksw
	case -iflip:
	    shift
	    @ actions++
	    echo "10 "$1" [INST_FLIP: lab MCS]" >> $act_tmp
	breaksw
	case -oflip:
	    shift
	    @ actions++
	    echo "4 "$1" [OBJ_FLIP: lab MCS]" >> $act_tmp
	breaksw
	case -sigmaflip:
	    set sigmaflip=1
	breaksw
	case -gflip:
	    shift
	    @ actions++
	    echo "3 "$1" [ORB_FLIP: lab MCS]" >> $act_tmp
	breaksw
	case -flipm:
	    shift
	    set dum=`echo $1|awk -F"," '{for(i=1;i<=NF;i++){printf $i" "}}'`
	    set FLIPMAN=($FLIPMAN $dum)
	    set manu=1
	    set fmantype=5
	breaksw
	case -iflipm:
	    shift
	    set dum=`echo $1|awk -F"," '{for(i=1;i<=NF;i++){printf $i" "}}'`
	    set FLIPMAN=($FLIPMAN $dum)
	    set manu=1
	    set fmantype=10
	breaksw
	case -oflipm:
	    shift
	    set dum=`echo $1|awk -F"," '{for(i=1;i<=NF;i++){printf $i" "}}'`
	    set FLIPMAN=($FLIPMAN $dum)
	    set manu=1
	    set fmantype=4
	breaksw
	case -swapd:  #swap def: takes 5 arguments
	    @ NSWAP++
	    @ actions++
	    shift
	    set SWAP=`echo $1`
	    shift
	    set SWAP=`echo $SWAP" "$1`
	    shift
	    set SWAP=`echo $SWAP" "$1`
	    shift
	    set SWAP=`echo $SWAP" "$1`
	    shift
	    set SWAP=`echo $SWAP" "$1`
	    set SWAPMAN=0
	    echo "2 "$SWAP" [SWAP: lab MCS CH1 CH2 RMIN RMAX]" >> $act_tmp
	breaksw
	case -swaps:
	    @ NSWAP++
	    @ actions++
	    shift
	    set SWAP=`echo $1`
	    if(-e INPUT/D04/swap.def)then
		set swapsdef=`awk 'FNR==1{printf $0}' INPUT/D04/swap.def`
	    else
		echo "File INPUT/D04/swap.def with 'swaps' specification not found"
		exit
	    endif
	    echo "2 $SWAP $swapsdef  # [short-swap]: MCS CH1 CH2 Rmin Rmax" >> $act_tmp
	breaksw
	case -swapl:
	    @ NSWAP++
	    @ actions++
	    shift
	    set SWAP=`echo $1`
	    if(-e INPUT/D04/swap.def)then
		set swapldef=`awk 'FNR==2{printf $0}' INPUT/D04/swap.def`
	    else
		echo "File INPUT/D04/swap.def with 'swapl' specification not found"
		exit
	    endif
#	    echo $swapldef
#	    exit
	    echo "2 "$SWAP" "$swapldef >> $act_tmp
	breaksw
	case -swapm:
	    shift
	    set SWAPMAN=`echo $SWAPMAN" "$1`
	    shift
	    set SWAPMAN=`echo $SWAPMAN" "$1`
	    @ SWAPMAN[1]++
	    set SWAP=0
	    set manu=1
	breaksw
	case -rcplus:
	    shift
	    set RCPLUS=$1
	breaksw
	case -rcutn:
	    shift
	    set RCUTN=$1
	breaksw
	case -xyzs:
	    set SAVEXYZS=1
	breaksw
	case -actions:
	    echo "d04 action names: "
	    $DECAHOME/scripts/d04tell action
	    exit
	breaksw
	case -debug:
	    echo "d04 debug options: "
	    $DECAHOME/scripts/d04tell debug
	    exit
	breaksw
	case -rel:
	    shift
	    @ RELAX=$1
	    @ actions++
	    echo "7 $RELAX $RELAXGAMMA $DRAMAX [RELAX: act_code STEPS GAMMA DRMAX]" >> $act_tmp
	breaksw
	case -ueff:
	    shift
	    set cueff=$1
	breaksw
	case -cmc:
	    shift
	    @ cmcsteps=$1
	    shift
	    set sigmc=$1
	    @ actions++
	    echo "9 $cmcsteps $sigmc [CMC: act_code STEPS SIGMA]" >> $act_tmp
	breaksw
	case -gamma:
	    shift
	    set RELAXGAMMA=$1
	breaksw
	case -drmax:
	    shift
	    set DRAMAX=$1
	breaksw
	case -ulevel:
	    shift
	    set level=$1
	breaksw
	case -tlevel:
	    shift
	    set tlevel=$1
	breaksw
	case -seed:
	    shift
	    set RSEED=$1
	breaksw
	case -savee:
	    shift
	    set SAVEE=$1
	breaksw
	case -couple:
	    set COUPLE=1
	breaksw
	case -pin:
	    shift
	    set pin=$1
	breaksw
	case -dfit:
	    @ actions++
	    echo "8  [DFIT]" >> $act_tmp
	    shift
	    set DFIT=1
	    goto skip_options
	breaksw
	case -nl:
	    shift
	    set mcl=$1
	breaksw
	case -lt:
	    shift
	    set nt=$1
	    shift
	    set t0=$1
	    shift
	    set t1=$1
	    set mct=1
	breaksw
	case -l:  # a MC step definition
	    @ mcs++
	    shift
	    set mc=($mc $1)
	    shift
	    set mc=($mc $1)
	breaksw
	case -beta:  # a MC step definition with single step
	    @ mcs++
	    shift
	    set mc=($mc 1 $1)
	breaksw
	case -lf:
	    shift
	    set mcname=$1  #MC schedule file
	    if !( -e $mcname ) then
		echo "MC schedule file $mcname doe snot exist."
		exit
	    endif
	breaksw
	case -hc:
	    shift
	    set hcap=$1
	breaksw
	case -dbg:
	    shift
	    set DBG=($DBG `echo $1 | awk '{split($1,a,",");for(i in a)print a[i]}'`)
	breaksw
	case -rec:
	    set FLIPREC=1
	breaksw
	case -rlist:
	    shift
	    @ RELAX=$1 # relaxation steps
	    set RELAXMAN=1
	    if ( -e rlist.inp ) then
		set RELMANLIST=`cat rlist.inp`
		@ RELAXMAN=$#RELMANLIST
	    else
		echo "Option -rlist requires file rlist.inp with space separated list of atoms for relaxation on the first line." | fold -s -w 70
		exit
	    endif
	breaksw
	case -vl:
	    shift
	    set IVI=$1
	breaksw
	case -temper:
	    set temper=1
	breaksw
	case -hl:
	    shift
	    set IHI=$1
#	    set HLW=$1
	breaksw
	case -hlw:
	    shift
	    set HLW=$1
	breaksw
	case -f:
	    shift
	    if !( -e $1 ) then
		echo "Tiling/config $1 does not exist."
		exit
	    endif
	    set FNAME=$1
	breaksw
	case -ch:
	    set CHEMINP=1
	breaksw
	case -chv:
	    shift
	    set chfi=$1
	    if (! -f $chfi) then
		echo "Chemistry file $chfi does not exist"
		exit
	    endif
	    shift
	    set chvar=$1
	    set havech=`cat $chfi | awk 'BEGIN{s=ARGV[1];ARGV[1]="-"}$1==s{ok=1}END{print ok}' $chvar`
	    if($havech != "1") then
		echo "Chem-variant definition $chvar undefined in $chfi"
		exit
	    endif
	    set CHEMINP=1
	breaksw
	case -chpinp:
	    if !( -f INPUT/chp.inp) then
		echo "Option -chp: file INPUT/chp.inp does not exits"
		exit
	    endif
	    set chpinp=1
	breaksw
	case -chp:
	    shift
	    set chpot=($chpot $1)
	    shift
	    set chpot=($chpot $1)
	    set chpot=($chpot 5) # default number of buffer sites
	    @ nchp++
	breaksw
	case -chb: #syntax: -chb Z1:POT1[:BUF1,Z2:POT2:Z2[...]]
	    shift
	    set nchp=`echo $1 | awk '{np=split($1,a,","); print np}'`
	    set chpot=($chpot `echo $1 | awk '{np=split($1,a,",");for(i=1;i<=np;i++){n=split(a[i],b,":"); if(n<3)b[3]=1000; for(j=1;j<=3;j++)print b[j]}}'`)
#	    echo "nchp="$nchp
#	    echo "chpot="$chpot
#	    exit
	breaksw
	case -r:
	    set RINP="INPUT/d04.inp"
	breaksw
	case -i:
	    shift
	    set RINP=$1
	breaksw
	case -a:
	    shift
	    set actname=$1
	    if !( -e $actname ) then
		echo "Actions file $actname does not exist."
		exit
	    endif
	breaksw
	case -test:
	    set TEST=1
	breaksw
	case -e:
	    set FORCETYPE0=1
	breaksw
	case -norun
	    set norun=1
	breaksw
	case -h:
	    goto helpmessage
	breaksw
	case -help:
	    helpmessage:
	    shift
	    if ( $#argv == 0 ) then
		$LSOPT
		exit
	    endif
	    $PHELP $1
	    exit
	breaksw
	default:
	    if ( -f "$1" ) then
		set FNAME="$1"
	    else
		echo 'd04: unrecognized option "'$1'". Available options: '
		$LSOPT
		exit
	    endif
	breaksw
    endsw
    shift
end
skip_options:

if ( $DFIT == 1 ) then
    $DECAHOME/scripts/dfit $FNAME $* -d04inp -loops $nt -betas $t0 $t1 > INPUT/dfit.inp
endif
if ( $level < 1 ) then
    echo "Object-update level must be at least 1."
    exit
endif
if !( -e $FNAME ) then
    echo "d04: Default input filename $FNAME does not exist."
    exit
endif
if !( -e $SRCDIR/tico.awk ) then
    echo "d04: Missing awk file $SRCDIR/tico.awk."
    exit
endif
# the following checks consistency of the input file
#awk -f $SRCDIR"/tico.awk" -s $FNAME
#exit
set FNOK=`awk -f $SRCDIR/tico.awk -s $FNAME`  #option -s tell tico to be silent
set TINP=$FNOK[1]
set ERR=$FNOK[2]
if ( $TINP > 0 ) then
    set rng=$#FNOK
    if ( $rng > 2 ) then
	set DECONAME1=$FNOK[3]
    else
	set DECONAME1=
    endif
endif
set ERRMSG=`echo $FNOK[4-]`
set TMSG=`echo "TILING CONFIG FLIP_REP"`
if ( $ERR > 0 ) then
    @ ind = $TINP + 1
    echo $FNAME" ("$TMSG[$ind]" type): "$ERRMSG
    if (( $FORCETYPE0 == 1 ) && ( $ERR > 4 ) && ( $TINP > 0 )) then
       @ ind = $TINP + 1
       echo "Error AFTER tiling section: forcing plain tiling input type."
       set TINP=0
    else
	exit
    endif
endif
# Files needed ultimately:
# INPUT/objects.def
if !( -e INPUT/objects.def ) then
    echo "d04: Input file INPUT/objects.def is required."
    exit
else
    set decotp=`awk 'FNR==2{print $1}' INPUT/objects.def`
#    set force3d=`awk 'FNR==2{print $2}' INPUT/objects.def`
endif
set INPTYPE=`head -2 INPUT/objects.def | awk 'FNR==2{print $1}'`
set DECONAME0=`head -1 INPUT/objects.def | awk 'FNR==1{print $1}'`
if (( $DECONAME0 == "" ) || !( -e $DECONAME0 )) then 
    echo "Line 1 of objects.def doesnt contain valid decoration filename. This could mean it is obsolete (rerun d00), or the original decoration was moved/renamed (deconame='"$DECONAME0"')." | fold -s -w 70
    exit
endif
#3D consistency check: we require that when 3D is on, tiling must have multi>1
set multi=`awk 'FNR==3{print $2}' $FNAME`

### I dont remember if this is up-to-date or to be definitely cut
#if(($force3d == 1) && ($multi < 2)) then
#    echo "Decoration rule defines 3D object(s), but tiling $FNAME has multi=$multi. This is not allowed (though could be, in principle)." | fold -s -w 70
#    exit
#endif

if($INPTYPE == 1) then
# Conditionally (atomic deco + pair pot) we need these files:
# pp.inp
# uc.inp
# atoms_para.def
    if !( -e INPUT/ap.def ) then
	echo "d04: INPUT-TYPE=1: file INPUT/ap.def is required."
	exit
    endif
    #check consistency config_para <-> objects.def
    if ( $TINP == "1" ) then  # CONFIG_PARA TYPE INPUT
	if (( $DECONAME1 == "" ) && ( $TINP == 1 )) then
	    echo "$FNAME is of config-type, but missing deconame (line3 col3)."
	    exit
	endif
	if (( $DECONAME1 == "" ) && ( $TINP == 2 )) then
	    echo "$FNAME is of flip-replay type, but missing deconame (line3 col3)."
	    exit
	endif
	if !( -e $DECONAME1 ) then
	    echo "d04: Decoration '$DECONAME1' from line 3 col 3 of '$FNAME' no longer exists!"
	    exit
	endif
if !( $DECONAME0 == $DECONAME1 ) then
	    echo "d04: "$FNAME" is decoration "$DECONAME1", but objects.def "$DECONAME0"."
	    echo -n "Rerun d00 "$DECONAME1" [y] ? "
	    set answer=$<
	    if !( $answer == "n" ) then
		echo d00 $DECONAME1
		d00 $DECONAME1 > _tmp
		set DECONAME0=$DECONAME1
	    else
		exit
	    endif
	endif
    endif
endif
if ( $TINP == 2 && $FLIPREC == 1 ) then
	echo "Input file is of flip-record type. Setting option 'rec' off."
	set FLIPREC=0
endif


# Creat backup copy of d04.inp, if this was not
if ( -e INPUT/d04.inp && !($RINP == "INPUT/d04.inp" ) && $manu != 1 ) then
    mv -f INPUT/d04.inp INPUT/d04.inp_prev
endif

if ( $RINP != 0 && $TEST == 1 ) then
    echo "Note: option -test suppresses option -rinf INPFILE, as it is designed to test autogenerated d04.inp (besides examination of the input config file)."|fold -s -w 70
    set RINP=0
endif
if ( $RINP != 0 ) then
    if !( -e $RINP ) then
	echo "Input file $RINP does not exist."
	exit
    endif
    set out=$RINP
    goto end
endif
set out="INPUT/d04.inp"
if ( $TEST == 1 ) then
    set out="/dev/stdout"
endif
echo "# Generated by script d04." > $out
if ( $#FLIPMAN > 0 || $SWAPMAN[1] > 0 || $RELAXMAN > 0 ) then
    rm -f $act_tmp
    echo "0 # ACTIONS (manual mode)" >> $out
    echo "1 1 # fake MC loops (manual mode)" >> $out
    echo "0 # MC schedule (manual mode)" >> $out
    goto skip_act_mc
endif
if ( $TINP == 2 ) then  # flip_replay
    rm -f $act_tmp
    echo "0 # ACTIONS (set by flip-rep mode)" >> $out
    echo "1 1 # fake MC loops" >> $out
    echo "0 # MC schedule" >> $out
    goto skip_act_mc
endif
# MC ACTIONS
set actnameb="INPUT/actions"
if ( $actname != 0 && $actions > 0 ) then # merge cmdline actions with actname
    set NACTR=`awk 'FNR==1{print $1}' $actname` # number of acts from actname
    @ NACT = $actions + $NACTR
    echo $NACT" # ACTIONS: $NACTR("$actname")+"$actions"(cmdline)" > $actnameb
    awk 'FNR==1{n=$1}FNR>1&&FNR<=n+1{print}' $actname >> $actnameb
    awk 'FNR==1{n=$1}FNR>1&&FNR<=n+1{print}' $act_tmp >> $actnameb
    cat $actnameb >> $out
else if ( $actions > 0 ) then
    echo -n $actions" " > $actnameb
    cat $act_tmp >> $actnameb
    cat $actnameb >> $out
else if ( $actname != 0 ) then
    awk 'FNR==1{n=$1;print $0}FNR>1&&FNR<=n+1{print $0}' $actname >> $out
else if ( $decotp == 0 ) then # the only action for tile-ham is flip
    echo "1  # action: via deco=0 in INPUT/objects.def" >> $out
    echo "5 1  [NODE_FLIP: lab MCS] (default for deco-less tham)" >> $out
else if ( $actname == 0 && $actions == 0 ) then
    rm -f $act_tmp
    echo "NO ACTION DEFINED (actions: -swaps, -swapl, -swapd, -swapm, -flip, -flipm, -rep, -rlist). The possibilities are: \n(i) define an action from the cmdline (options -flip -flipm -swaps -swapl -swapd -swapm -rel -rep -rlist); \n(ii) read actions file (option -a) \n(iii) use option -rinp to recycle previously used INPUT/d04.inp, as long as one already exists. \nNote that MC actions (-flip -swapl -swaps -swapd -rel) require a MC schedule, unlike the 'manual' actions (-flipm -swapm -rlist). " | fold -s -w 70
    echo '- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -'
    echo 'List all available options by "d04 -h".'
    echo 'Type "d04 -help OPTION" for details.'
    exit
endif
rm -f $act_tmp
# MC_SCHEDULE
echo $IVI" "$IHI"  [MC: VERTICAL_LOOPS HORIZONTAL_LOOPS]" >> $out
if ( $mcs > 0 || $mct > 0 ) then 
    if ( $mcname != 0 ) then 
	echo 'MC schedule entries invoked from commandline ("-l or -lt") override MC schedule via option "-lf". Entries from the file $mcname will be ignored. (Because it does not make a sense to merge the two without specifying precise order of the entries.)' | fold -s -w 70
	set mcname=0
    endif
endif
set mcnameb=".mc_sched.tmp"
if ( $mcs > 0 ) then  # MC schedule from cmdline
    echo $mcs" # MC schedule (cmdlopt -l)" > $mcnameb
    @ I = 1
    while( $I <= $mcs )
	@ J = 2 * ( $I - 1 ) + 1
	@ K = $J + 1
	@ mm = $mc[$J] * $mcl
	echo $mm" "$mc[$K]"  #   MCS beta" >> $mcnameb
	@ I++
    end
else if ( $mct == 1 ) then # linear mc schedule; better go awk!
    if ( $nt < 2 ) then
	echo 'Linear MC schedule must define at least 2 temperatures. First parameter after "-lt nt t0 t1" must be > 1. Current nt='$nt'.' | fold -s -w 70
	exit
    endif
    echo "do_nothing" | awk -f $SRCDIR/d04_mct.awk $mcl $nt $t0 $t1 > $mcnameb
else if ( $mcname != 0 ) then
    awk 'BEGIN{nl=ARGV[2];ARGC-=1}FNR==1{nn=$1;print $1, " # MC schedule from "FILENAME" mult by "nl" via option -nl"}FNR>1&&FNR<=nn+1{print nl*$1, $2, "MCS beta"}' $mcname $mcl > $mcnameb
else if ( $DFIT == 1 || $RELAX > 0 ) then
    echo "1 # fake T-loop by relax||dfit option" > $mcnameb
    echo "1 1 # fake relax/dfit T-schedule" >> $mcnameb
else
    echo '(d04): Undefined MC schedule. There are 4 ways to define one: \n(i) from the cmdline via option "-l" (this can be used repetitively to add new entries); \n(ii) read schedule from a mc_schedule file via option -lf (see a sample in INPUT/D04/mc_schedule, or use it via "-lf INPUT/D04/mc_schedule"); \n(iii) use -r option to reuse previous autogenerated INPUT/d04.inp, as long as one existed (or "-i INPUT_FILE"). \n(iv) use "-lt NTEMP BETA0 BETA1" option for automatic linear annealing schedule. This is most handy approach: afterwards you can edit this schedule by hand (it will be saved in INPUT/mc_schedule.)\nNote you dont need a schedule for "manual" operations (-flipm, -swapm, -rlist)' | fold -s -w 70
    echo '- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -'
    echo 'List all available options by "d04 -h".'
    echo 'Type "d04 -help OPTION" for details.'
    exit
endif
if ( $hcap > 0 ) then
    awk 'BEGIN{na=ARGV[2];ARGC-=1}\
	FNR==1{nn=$1;print nn*2" # MC schedule for heat-capacity measurement (via -hc "na")"}\
	FNR==2{print $1*na, $2"  initial equilibration"; print $1*na, $2"  measurement"}\
	FNR>2{print $1, $2"  equilibration"; print $1*na, $2"  measurement"}\
	' $mcnameb $hcap > INPUT/mc_schedule	
else
    cat $mcnameb > INPUT/mc_schedule
endif
rm -f $mcnameb
cat INPUT/mc_schedule >> $out
skip_act_mc:
echo "$FLIPREC # [FLIPREC]" >> $out
echo "$#FLIPMAN $fmantype $FLIPMAN # [FLIPMAN]" >> $out
echo "$SWAPMAN # [SWAPMAN]" >> $out
echo "$RELAXMAN $RELAX $RELAXGAMMA $DRAMAX $RELMANLIST # [RELAXMAN: NATOMS STEPS GAMMA DRMAX ATOMLIST]" >> $out
echo "$NFD  $FLIPDEFS # [FLIPDEF: nu_from nu_to ... for flips]" >> $out 
echo "$sigmaflip  # [0=hex-flip 1=2-level sigma-flip]" >> $out
echo "$level $tlevel # [level,tlevel: 1=hex-surf, N= extend boundary (N-1) times]" >> $out
echo "$COUPLE # [couple: flip skinny rhombus first, whenever it makes a fat flippable]" >> $out
echo "$pin # [pin: pin a tiling vertex to avoid drift]" >> $out
echo "$cueff # [cueff]" >> $out
echo "$RCUTN # [RCUTN]" >> $out
echo "$RCPLUS # [RCPLUS]" >> $out
echo "$FEPS # [FLIP_UNION_EPS]" >> $out
echo "$RSEED # [seed for random number generator]" >> $out
echo "$SAVEXYZS # [save xyzs for projected density plot]" >> $out
echo "$SAVEE # [record every N-th dU]" >> $out
echo "$HLW # save config for every horiz loop while h-loop index I<=HLW" >> $out
echo "$#DBG $DBG [DEBUG: N_opt opt_list]" >> $out

# CHEMISTRY REDEF
echo "$CHEMINP [chemistry redefinition]" >> $out
if ( $CHEMINP == 1 ) then
    if($chfi == "") then
	set CHINP=`awk 'BEGIN{a="undef"}/^</{a=substr($0,2)}END{print a}' INPUT/D04/chemistry`
	if ( $CHINP[1] == "undef" ) then 
	    echo "Chemistry redef [option -ch]: no valid input in INPUT/D04/chemistry." > /dev/stderr
	    exit
	endif
    else
	set CHINP=`cat $chfi | $DECAHOME/scripts/ichdef $chvar`
	if ($#CHINP < 2) then
	    echo "Improper chemistry definition : code $CHINP"
	    echo "Check chemistry file $chfi"
	    exit
	endif
    endif
    echo $CHINP >> $out
endif
if ($chpinp == 0) then
    echo "$nchp $chpot [chemical potentials]" >> $out
else
    head -1 INPUT/chp.inp >> $out
endif
echo "$DFIT [diffraction data fit: input file dfit.inp]" >> $out
if ( $TEST == 1 ) then 
    @ ind = $TINP + 1
    echo "####################################################"
    echo "Input type: "$TINP
    echo $FNAME" ("$TMSG[$ind]" type) should work."
    exit
endif
end: 

set read_tvl=`head -3 $FNAME|tail -1|awk '{for(i=1;i<=NF;i++){na=split($i,a,"=");if(na=2&&a[1]=="read_tvl")print "1"}}'`
if($read_tvl == "") set read_tvl=0

echo "d04 "$commandline >> INPUT/.d04cmdline
## only one identical line is shown
awk '{s[$0]++; if(s[$0]==1)x=x$0"\n"}END{printf x}' INPUT/.d04cmdline > INPUT/d04.cmdline
echo $FNAME>.d04inp
echo $TINP>>.d04inp
echo $read_tvl>>.d04inp
echo $out>> .d04inp
$EXEC
if ($temper == 1) then # make summary
    set t=`cat Trun`
    set e=`cat Ef`
    echo $t $e >> elist
    cat e.min >> emins
endif
if ($chvar != "") then
    echo "Moving [copa&&xyz].min -> $chvar"
    cp copa.min copa.$chvar
    cp xyz.min xyz.$chvar
endif
##

